# encoding:utf-8
import json
import os
import re
import shutil
import time

import threadpool
from unipath import FILES, DIRS, Path

api_key = 'fd06d5cdeb404dbcb0dc79312e795a61'
domain = 'http://localhost:8096'
image_root_path = ''
local_path = None
gd_path = None
# 视频文件
video_type = ['.mp4', '.avi', '.rmvb', '.wmv', '.mov', '.mkv', '.flv', '.ts', '.webm', '.iso', '.mpg']
# 图片文件
download_type = ['.srt', '.ass', '.jpg', '.png', '.nfo']

# 字幕类型
subtitles_type = ['.srt', '.ass']

error_path = []

last_dir_list = []

mapping_gd_ld = []


# 获取最后一级文件夹
def find_all_dir(dir_path):
    dir_count = 0
    for item_path in os.listdir(dir_path):
        temp_path = Path(dir_path, item_path)
        if os.path.isdir(temp_path):
            dir_count = dir_count + 1
            find_all_dir(temp_path)
    if dir_count == 0:
        print('[+] {0}'.format(dir_path))
        last_dir_list.append(dir_path)


# 镜像到本地文件夹
def mirror_gd_local():
    for root, dirs, files in os.walk(local_path):
        for item in files:
            print('[#] {0}'.format(item))
            if Path(root, item).size() == 0:
                Path(root, item).remove()

    dirs = gd_path.listdir()
    # 线程池
    pool = threadpool.ThreadPool(15)
    requests = threadpool.makeRequests(mirror_copy, dirs)
    [pool.putRequest(req) for req in requests]
    pool.wait()

    print("********************************")
    print("******** 异常的路径")
    print("********************************")
    for item in error_path:
        print(item)
    print("保存映射关系")
    with open('./scrapy_result/mapping_gd_ld.json'.format(str(int(time.time()))), 'w+', encoding='utf-8') as file:
        file.write(json.dumps(mapping_gd_ld, ensure_ascii=False))
    # 反向对比
    remove_local_dir()


def mirror_gd_local_jav():
    for root, dirs, files in os.walk(local_path):
        for item in files:
            print('[#] {0}'.format(item))
            if Path(root, item).size() == 0:
                Path(root, item).remove()

    dirs = gd_path.listdir()
    count = 0
    count_all = str(len(dirs))
    print('[+] 找到 {0} 个子文件夹'.format(count_all))
    for item_dir in dirs:
        count = count + 1
        print('[!] - ' + str(count / int(count_all) * 100)[:4] + '%' + ' [' + str(count) + '/' + count_all + '] - ' + item_dir)
        # 线程池
        pool = threadpool.ThreadPool(15)
        requests = threadpool.makeRequests(mirror_copy, item_dir.listdir())
        [pool.putRequest(req) for req in requests]
        pool.wait()

    print("********************************")
    print("******** 异常的路径")
    print("********************************")
    for item in error_path:
        print(item)
    # 反向对比
    remove_local_dir()


def mirror_file(source_file_path, targer_file_path):
    """
        镜像文件
    :param source_file_path:
    :param targer_file_path:
    :return:
    """
    mapping_gd_ld.append("/".join(source_file_path.replace(gd_path + "\\", '').split("\\")))
    # 文件已经存在
    if targer_file_path.exists():
        print("[E]  " + targer_file_path)
        return
    try:
        # 视频文件
        if targer_file_path.ext.lower() in video_type:
            print("[A]  " + source_file_path)
            file_stream = open(targer_file_path, "wb", buffering=0)
            file_stream.close()
            return

        # 需要复制的文件
        if source_file_path.ext.lower() in download_type:
            source_file_path.copy(targer_file_path)
    except Exception as ex:
        print("[#] #################")
        print("[#] " + repr(ex))
        print("[#] " + targer_file_path)
        print("[#] #################")
        error_path.append(source_file_path)
        # targer_file_path.rmtree(True)


# 本地和网盘数据同步
def remove_local_dir():
    for root, dirs, files in os.walk(local_path):
        print("[!]  {0}".format(root))

        # ---------- 删除文件夹
        root = Path(root)
        if not root.exists():
            continue
        # 目标路径
        tar_dir_path = Path(root.replace(local_path, gd_path))
        if not tar_dir_path.exists():
            Path(root).rmtree()
            print("[D]  {0}".format(root))
            continue

        # 删除文件
        for item_file_path in files:
            target_file_path = Path(Path(root, item_file_path).replace(local_path, gd_path))
            print("[+]    {0}".format(target_file_path))
            if target_file_path.exists():
                continue
            Path(root, item_file_path).remove()


# 生成目录结构
def create_file_path_info(root_dir_path):
    log_txt = open("/content/dir_info.txt", "wb", buffering=0)
    for root, dirs, files in os.walk(root_dir_path):
        for item_file_path in files:
            print('[+] {0}'.format(os.path.join(root, item_file_path)))
            log_txt.write((str(os.path.join(root, item_file_path)) + '\n').encode('utf8'))
    log_txt.close()


# -------------------------------- 处理tmm结果

def process_tmm_log(log_file_path, root_dir_path):
    readlines_arr = get_txt_content(log_file_path)
    if len(readlines_arr) == 0:
        print("[!] {0}".format("暂无数据"))
        return
    file_path_mapping = []
    folder_path_mapping = []
    for item in readlines_arr:
        item = item.strip()
        if len(item) == 0:
            continue

        if ".deletedByTMM" in item:
            continue

        if r"C:\Users\ADMINI~1\AppData\Local\Temp" in item:
            continue

        if 'Successfully moved file from' in item:
            result = re.match(r'.*?Successfully\s*moved\s*file\s*from\s+(.*)', item, re.IGNORECASE)
            if result:
                file_path_mapping.append(result.group(1).split(" to "))
                print('[+] {0}'.format(item))
            continue

        if ' Successfully moved folder' in item:
            result = re.match(r'.*?Successfully\s*moved\s*folder\s+(.*)', item, re.IGNORECASE)
            if result:
                folder_path_mapping.append(result.group(1).split(" to "))
                print('[+] {0}'.format(item))

    # # 处理原始文件
    # print("# ########################")
    # print("# 处理原始文件")
    # print("# ########################")
    # for item in file_path_mapping:
    #     item[0] = "/".join(item[0].replace(source_root_path + "\\", '').split("\\"))
    #     print('[F] {0}'.format(item[0]))
    #
    # print("# ########################")
    # print("# 处理后续文件")
    # print("# ########################")
    for item in folder_path_mapping:
        print('[D] {0}'.format(item[1]))
        for item_sub in file_path_mapping:
            item_sub[1] = item_sub[1].replace(item[0], item[1])
            # item_sub[1] = '/'.join(item_sub[1].replace(item[0], item[1]).replace(source_root_path + "\\", '').split("\\"))
        item[0] = "/".join(item[0].replace(root_dir_path + "\\", '').split("\\"))
        item[1] = "/".join(item[1].replace(root_dir_path + "\\", '').split("\\"))

    for item in file_path_mapping:
        item[0] = "/".join(item[0].replace(root_dir_path + "\\", '').split("\\"))
        item[1] = "/".join(item[1].replace(root_dir_path + "\\", '').split("\\"))

    with open('./scrapy_result/process_info.json', 'w+', encoding='utf-8') as file:
        file.write(json.dumps({'files': file_path_mapping, 'folder': folder_path_mapping}, ensure_ascii=False))


# 读取文本内容
def get_txt_content(file_path):
    txt_arr = []
    for item in ["utf8", "gbk", "utf16"]:
        try:
            with open(file_path, 'r', encoding=item) as fh:
                txt_arr = fh.readlines()
                break
        except:
            print("[!] 读取失败")
    return txt_arr


# 最终整理，gd和ld的关系
def reand_mapping_tmm(gd_root_path, ld_root_path):
    with open('./scrapy_result/mapping_gd_ld.json', 'r', encoding='utf-8') as file:
        local_gd_ld = json.load(file)

    with open('./scrapy_result/process_info.json', 'r', encoding='utf-8') as file:
        local_process_info = json.load(file)

    # tmm 处理过的文件
    local_process_files = local_process_info['files']
    local_process_folder = local_process_info['folder']
    # 只处理视频
    # 对session有过处理的
    first_step_mapping = []
    for item in local_gd_ld:
        print('[01] {0}'.format(item))
        if Path(item).ext.lower() not in video_type:
            continue

        is_find = False
        # 是
        for sub_item in local_process_files:
            if item[1] == sub_item[0]:
                item[1] = sub_item[1]
                first_step_mapping.append(item)
                is_find = True
                break
        if not is_find:
            first_step_mapping.append(item)

    # 只处理文件夹名称
    for item in first_step_mapping:
        print('[02] {0}'.format(item))
        for sub_item in local_process_folder:
            if sub_item[0] == item[1].split("//")[0]:
                # 替换路径
                item[1] = item[1].replace(sub_item[0], sub_item[1])
                break

    # 对比本地映射，删除不存在的路径
    for i in range(len(first_step_mapping) - 1, -1, -1):
        item = first_step_mapping[i]
        print('[03] {0}'.format(item))
        if not Path(ld_root_path, item[1]).exists():
            first_step_mapping.pop(i)

    # 处理目录
    for item in first_step_mapping:
        print('[04] {0}'.format(item))
        item[0] = '/'.join(item[0].split("\\"))
        item[1] = '/'.join(item[1].split("\\"))
    # final_mapping_two = []
    # for item in first_step_mapping:
    #     # 如果不存在就退出
    #     # if not Path(item[1]).exists():
    #     #     continue
    #
    #     print('----------------')
    #     item[0] = "/".join(item[0].replace(gd_path + "\\", '').split("\\"))
    #     print("[+] {0}".format(item[0]))
    #     item[1] = "/".join(item[1].replace(local_path + "\\", '').split("\\"))
    #     final_mapping_two.append(item)

    with open('./scrapy_result/final_result.json', 'w+', encoding='utf-8') as file:
        file.write(json.dumps(first_step_mapping, ensure_ascii=False))


def reand_mapping_tmm_new(dir_path):
    dir_path = Path(dir_path)
    if not dir_path.exists():
        print("[!] 文件夹不存在")
        return

    # 加载网盘文件
    with open('./scrapy_result/mapping_gd_ld.json', 'r', encoding='utf-8') as file:
        gd_file_arr = json.load(file)

    # 加载本地文件
    local_file_arr = []
    for item_file in dir_path.walk(filter=FILES):
        print(item_file)
        if item_file.ext.lower() in video_type:
            local_file_arr.append(item_file)

    final_result = []
    for item in local_file_arr:
        print("[+] {0}".format(item))
        for sub_item in gd_file_arr:
            if Path(item).name == Path(sub_item).name:
                final_result.append(["/".join(sub_item.split("\\")), "/".join(item.replace(dir_path + "\\", '').split("\\"))])

    with open('./scrapy_result/final_result.json', 'w+', encoding='utf-8') as file:
        file.write(json.dumps(final_result, ensure_ascii=False))


# -------------------------------- colib
# 移动视频文件
def process_gd_dir_path(result_json_path, source_root_path, targer_root_path):
    with open(result_json_path, 'r', encoding='utf-8') as file:
        load_result = json.load(file)

    for item in load_result:
        print("--------------------------")
        source_file_path = Path(source_root_path, '/'.join(item[0].split('\\')))
        targer_file_path = Path(targer_root_path, '/'.join(item[1].split('\\')))
        print(source_file_path)
        print(targer_file_path)
        if not source_file_path.exists():
            print("[N] 目标文件不存在")
            continue
        # 如果已经存在，就删除
        if targer_file_path.exists():
            if targer_file_path.size() == 0:
                targer_file_path.remove()
            else:
                continue

        # https://blog.csdn.net/qq_27283619/article/details/96709949
        source_file_path.rename(targer_file_path, True)


# ==================== 检查文件夹是否合格
def check_movie(param_input_dir):
    import os
    from unipath import Path
    temp_video_type = ['.mp4', '.avi', '.rmvb', '.wmv', '.mov', '.mkv', '.flv', '.ts', '.webm', '.iso']
    dirs = os.listdir(param_input_dir)
    count = 0
    count_all = str(len(dirs))
    print('[+]找到', count_all, ' 文件夹')
    error_arr = []
    question_arr = []
    for dir_name in dirs:
        count = count + 1
        percentage = str(count / int(count_all) * 100)[:4] + '%'
        print('[!] ------------- ' + percentage + ' [' + str(count) + '/' + count_all + '] -------------')
        print("[!] 处理目录 : " + dir_name)
        # 文件夹路径
        source_dir_path = Path(param_input_dir, dir_name)
        nfo_file_list = []
        jpg_file_list = []
        movie_file_list = []
        for item_file_name in os.listdir(source_dir_path):
            # nfo文件
            if item_file_name == 'movie.nfo':
                nfo_file_list.append(Path(source_dir_path, item_file_name))
                continue
            # 图片文件
            if item_file_name == 'fanart.jpg' or item_file_name == 'poster.jpg' or item_file_name == 'thumb.jpg':
                jpg_file_list.append(Path(source_dir_path, item_file_name))
                continue
            # 视频文件
            if Path(item_file_name).ext.lower() in temp_video_type:
                movie_file_list.append(Path(source_dir_path, item_file_name))
                continue
        if len(movie_file_list) > 1:
            question_arr.append(source_dir_path)
        try:
            if len(nfo_file_list) == 0 or len(jpg_file_list) == 0 or len(movie_file_list) == 0:
                error_arr.append(source_dir_path)
        except:
            print("  [-] 操作异常")

    print("******************* 缺失文件 **********************")
    for item in error_arr:
        print(item)

    print("******************* 有多个视频文件 **********************")
    for item in question_arr:
        print(item)
    print("[*]============================处理完成==========================")


# ==================== 移动文件到正式目录


# 移动文件
# import os
# from unipath import FILES
def move_dir_to_dir(param_source_dir, param_targer_dir, param_will_delete_dir, param_forced_replace):
    param_will_delete_dir = Path(param_will_delete_dir)
    if not param_will_delete_dir.exists():
        param_will_delete_dir.mkdir(True)

    dirs = os.listdir(param_source_dir)
    count = 0
    count_all = str(len(dirs))
    print('[+]找到 {0} 文件夹'.format(count_all))
    for dir_name in dirs:
        print("[*]======================================================")
        count = count + 1
        percentage = str(count / int(count_all) * 100)[:4] + '%'
        print('   [!] - ' + percentage + ' [' + str(count) + '/' + count_all + '] - ' + dir_name)
        # 文件夹路径
        source_dir = Path(param_source_dir, dir_name)
        targer_dir = Path(param_targer_dir, dir_name)
        # 如果不存在，就直接替换
        if not targer_dir.exists():
            print("   [+] " + source_dir.stem + " -> " + targer_dir)
            source_dir.rename(targer_dir)
            continue

        print("   [-] 文件夹重复")
        if param_forced_replace:
            print("   [-] 强制替换")
            targer_dir.move(param_will_delete_dir)
            source_dir.rename(targer_dir)
            continue
        print("   [!] ------------------------------")
        source_dir_size = calcu_dir_sieze(source_dir)
        target_dir_size = calcu_dir_sieze(targer_dir)
        print("   [!] ------------------------------")
        print("   [!] " + source_dir + " " + str(source_dir_size) + " GB")
        print("   [!] " + targer_dir + " " + str(target_dir_size) + " GB")

        # 如果目标文件夹大于13G就不处理
        if target_dir_size >= 13:
            print("   [-] 目标文件夹大于 13G 不需要处理")
            continue

        if source_dir_size > 19:
            print("   [-] 源文件夹大于 19G 不需要处理")
            continue

        if target_dir_size >= source_dir_size:
            print("   [-] 源文件夹【小于】目标文件夹不需要处理")
            continue

        targer_dir.move(param_will_delete_dir)
        source_dir.rename(targer_dir)
        print("   [+] " + source_dir.stem + " -> " + targer_dir)

    print("[*]============================处理完成==========================")


# 获取文件夹大小
def calcu_dir_sieze(param_dir_path):
    temp_video_type = ['.mp4', '.avi', '.rmvb', '.wmv', '.mov', '.mkv', '.flv', '.ts', '.webm', '.iso']
    file_size = 0
    for sub_file_path in Path(param_dir_path).walk(filter=FILES):
        if sub_file_path.ext.lower() in temp_video_type:
            temp_file_size = round(os.path.getsize(sub_file_path) / 1024 / 1024 / 1024, 2)
            file_size = file_size + temp_file_size
            print("   [!] == （{0} GB）{1}".format(str(temp_file_size), sub_file_path))
    return file_size


# ==================== 回滚删除的文件
# 错误处理
def reback_file_by_log():
    readlines_arr = get_txt_content(r'./scrapy_result/delete_file_log.txt')
    if len(readlines_arr) == 0:
        print("[!] {0}".format("暂无数据"))
        return
    for item in readlines_arr:
        temp_file_path = Path(item.replace("\n", ""))
        if temp_file_path.exists():
            print('[-] 已存在 {0}'.format(temp_file_path.name))
            continue
        file_stream = open(temp_file_path, "wb", buffering=0)
        file_stream.close()
        print('[+] 已创建 {0}'.format(temp_file_path.name))


# 删除目录内的视频
def clear_dir_context(root_dir_path):
    log_txt = open(r'./scrapy_result/delete_file_log.txt', "wb", buffering=0)
    for item in Path(root_dir_path).walk(filter=FILES):
        if item.ext.lower() in video_type:
            print('[-] {0}'.format(item))
            item.remove()
            log_txt.write('{0}\n'.format(item).encode('utf8'))
    log_txt.close()


def ss(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        load_result = json.load(file)
    for item in load_result:
        item[0] = item[0].replace("Y:\\动漫资源\\其他资源\\动漫剧\\", "")
        item[1] = item[1].replace("E:\\meta-data\\数据工厂\\", "")
        print(item)

    with open('./scrapy_result/mapping_gd_ld.json', 'w+', encoding='utf-8') as file:
        file.write(json.dumps(load_result, ensure_ascii=False))


# ---------------------------- 新

# 复制文件到本地
def mirror_copy(source_root_dir_path, target_root_dir_path):
    print(source_root_dir_path)
    print(target_root_dir_path)
    # 获取文件夹下的所有文件
    for item_dir in Path(source_root_dir_path).walk(filter=DIRS):
        for item_file in item_dir.walk(filter=FILES):
            # 替换路径
            target_file_path = Path(item_file.replace(source_root_dir_path, target_root_dir_path))
            # 文件已经存在
            if target_file_path.exists():
                print("[!]  " + target_file_path)
                continue
            try:
                target_file_path.parent.mkdir(True)
                # 视频文件
                if target_file_path.ext.lower() in video_type:
                    print("[+]  " + target_file_path)
                    # 创建新文件
                    # file_stream = open(target_file_path, "wb", buffering=0)
                    # file_stream.close()
                    Path("./scrapy_result/source_move_file.mkv").copy(target_file_path)
                    continue
                # 需要复制的文件
                if target_file_path.ext.lower() in []:
                    print("[+]  " + target_file_path)
                    item_file.copy(target_file_path)
            except Exception as ex:
                print("[#] #################")
                print("[#] " + repr(ex))
                print("[#] #################")
                # targer_file_path.rmtree(True)

    for item_dir in Path(source_root_dir_path).listdir():
        # 替换路径
        target_file_path = Path(item_dir.replace(source_root_dir_path, target_root_dir_path))
        # 文件已经存在
        if target_file_path.exists():
            print("[!]  " + target_file_path)
            continue
        try:
            target_file_path.parent.mkdir(True)
            # 视频文件
            if target_file_path.ext.lower() in video_type:
                print("[+]  " + target_file_path)
                # 创建新文件
                # file_stream = open(target_file_path, "wb", buffering=0)
                # file_stream.close()
                Path("./scrapy_result/source_move_file.mkv").copy(target_file_path)
                continue
            # 需要复制的文件
            if target_file_path.ext.lower() in download_type:
                print("[+]  " + target_file_path)
                item_dir.copy(target_file_path)
        except Exception as ex:
            print("[#] #################")
            print("[#] " + repr(ex))
            print("[#] #################")
            # targer_file_path.rmtree(True)


# 修改文件名后缀
def edit_ext(param_path):
    # 获取文件夹下的所有文件
    for item in Path(param_path).walk(filter=FILES):
        print("[F]  " + item)
        # 处理文件
        if item.ext.lower() in video_type:
            # 文件名称
            new_file = Path(Path(item).parent, Path(item).name + '.laoji')
            # 如果存在就跳过
            if not new_file.exists():
                print("[A]  " + new_file)
                # 创建新文件
                file_stream = open(new_file, "wb", buffering=0)
                file_stream.close()
            # 删除旧文件
            item.remove()


# 通过.laoji的文件创建视频文件
def back_edit_ext(root_path):
    """
    修改视频文件扩展名
    :param root_path: 根目录路径
    :return:
    """
    # 获取文件夹下的所有文件
    for item_file in Path(root_path).walk(filter=FILES):
        # 如果不是.laoji后缀的文件就跳过
        if item_file.ext.lower() not in ['.laoji']:
            continue
        # 如果文件存在就删除
        target_file_path = Path(item_file.parent, item_file.stem)
        if target_file_path.exists():
            target_file_path.remove()
        try:
            print('{} -> {}'.format(item_file, target_file_path.parent))
            Path("./scrapy_result/source_move_file.mp4").copy(target_file_path)
            # file_stream = open(target_file_path, "wb", buffering=0)
            # file_stream.close()
        except Exception as ex:
            print("[#] #################")
            print("[#] " + repr(ex))
            print("[#] #################")
            # targer_file_path.rmtree(True)


# 源文件和目标文件建立关系
def source_relation_targer(source_file_path, targer_file_path):
    source_file = []
    targer_file = []

    # 所有源文件
    for item_dir in source_file_path:
        for item in Path(item_dir).walk(filter=FILES):
            print("[S==>]  " + item)
            if item.ext.lower() in ['.laoji']:
                source_file.append(item)

    # 所有目标文件
    for item_dir in targer_file_path:
        for item in Path(item_dir).walk(filter=FILES):
            print("[T]-->" + item)
            if item.ext.lower() in video_type:
                targer_file.append(item)

    for item_source in source_file:
        for item_targer in targer_file:
            if item_source.stem.replace(".laoji", "") == item_targer.name:
                print("{} ---> {}".format(item_targer, item_source.parent))
                item_targer.move(item_source.parent)
                break


def mapping_file_with_video(source_dir_path, targer_dir_path):
    """
    1、文件映射
    :param source_dir_path: 源目录
    :param targer_dir_path: 目标目录
    :return:
    """
    # E:\emby\高清动画
    # E:\emby\文件映射
    source_dir_path = Path(source_dir_path)
    # E:\emby\文件映射\高清动画
    targer_dir_path = Path(targer_dir_path, source_dir_path.name)
    # Y:\115\影视剧集\高清动画
    target_cloud_dir_path = Path(r'Y:\115\影视剧集', source_dir_path.name)
    # 获取所有的视频文件
    for item in source_dir_path.walk(filter=FILES):
        print("[+]  " + item)
        # 如果是字幕就复制过去
        if item.ext.lower() in subtitles_type:
            targer_file_path = Path(item.replace(source_dir_path, targer_dir_path))
            # 如果文件存在就删除
            if targer_file_path.exists():
                targer_file_path.remove()
            item.copy(targer_file_path)
            continue

        # 如果不是视频文件不处理
        if item.ext.lower() in video_type:
            source_file_path = Path(item.replace(source_dir_path, targer_dir_path))
            targer_file_path = Path(item.replace(source_dir_path, target_cloud_dir_path))
            # 执行命令
            cmd = 'mklink "{}" "{}"'.format(
                source_file_path,
                targer_file_path
            )
            os.system(cmd)


# 迁移映射文件和字幕
def movie_video_subtitle(source_dir_path, targer_dir_path):
    """
    1、文件映射
    :param source_dir_path: 源目录
    :param targer_dir_path: 目标目录
    :return:
    """
    # E:\emby\高清动画
    # E:\emby\文件映射
    source_dir_path = Path(source_dir_path)
    # E:\emby\文件映射\高清动画
    targer_dir_path = Path(targer_dir_path, source_dir_path.name)

    # 获取所有的视频文件
    for item in source_dir_path.walk(filter=FILES):
        print("[+]  " + item)
        # 如果是字幕就复制过去
        if item.ext.lower() in subtitles_type:
            targer_file_path = Path(item.replace(source_dir_path, targer_dir_path))
            if not targer_file_path.parent.exists():
                targer_file_path.parent.mkdir(True)
            # 如果文件存在就删除
            if targer_file_path.exists():
                targer_file_path.remove()
            item.copy(targer_file_path)
            continue

        if item.ext.lower() in video_type:
            targer_file_path = Path(item.replace(source_dir_path, targer_dir_path))
            if not targer_file_path.parent.exists():
                targer_file_path.parent.mkdir(True)
            # 如果文件存在就删除
            if targer_file_path.exists():
                targer_file_path.remove()
            item.copy(targer_file_path)


def mapping_sigle_file(source_file_path, targer_file_path):
    """
    单个文件映射
    :param source_file_path: 源文件
    :param targer_file_path:目标文件
    :return:
    """
    # 清空给所有的软连接
    for item in Path(source_file_path).walk(filter=FILES):
        if item.islink():
            item.remove()
            print("删除：{}".format(item))

    # 所有源文件
    for item in Path(source_file_path).walk(filter=FILES):
        if item.ext.lower() in ['.laoji']:
            temp_target_file_path = Path(item.parent.replace(Path(source_file_path).parent, targer_file_path), item.stem.replace(".laoji", ""))
            # 执行命令
            cmd = 'mklink "{}" "{}"'.format(Path(item.parent, item.replace(".laoji", "")), temp_target_file_path)
            os.system(cmd)


# 验证重复的数据
def validate_dir(source_file_path, targer_file_path, del_loacl, is_del):
    """
    验证数据并且删除
    :param source_file_path: 本地数据
    :param targer_file_path: 云端数据
    :param del_loacl:  true：删除本地，false：删除云端
    :param is_del true：删除，false：不删除
    :return:
    """
    source_dir = []
    targer_dir = []

    # 所有源文件
    for item in Path(source_file_path).listdir():
        print("[==>]  " + item)
        source_dir.append(item)

    # 所有目标文件
    for item in Path(targer_file_path).listdir():
        print("[-->]  " + item)
        targer_dir.append(item)

    # 查找重复
    for item in targer_dir:
        for sub_item in source_dir:
            if item.stem == sub_item.stem:
                try:
                    if del_loacl:
                        print("[D]  " + sub_item)
                        if is_del:
                            shutil.rmtree(sub_item)
                    else:
                        print("[D]  " + item)
                        if is_del:
                            shutil.rmtree(item)

                except Exception as ex:
                    print("[#] #################")
                    print("[#] " + repr(ex))
                    print("[#] " + targer_file_path)
                    print("[#] #################")
                break


# 删除软连接
def remove_lik(source_dir_path):
    # 清空给所有的软连接
    for item in Path(source_dir_path).walk(filter=FILES):
        if item.islink():
            print(item)
            item.remove()


# https://www.jb51.net/article/170248.htm
# pip install -r requirements.txt #使用requirements.txt安装依赖的方式：
# pip install pipreqs #安装
# pipreqs . --encoding=utf8 --force # 在当前目录生成

# python .\mirror-tools.py
if __name__ == '__main__':
    # ----------------------------
    # 1、将115的数据奖项
    mirror_copy(r'Y:\115\影视剧集\数据工厂\邵氏电影', r"E:\临时文件\meta-data")
    # 2、修改视频文件后缀
    # edit_ext(r'E:\临时文件\meta-data')
    # back_edit_ext(r'E:\临时文件\meta-data')
    # 3、验证重复
    # validate_dir(r"E:\临时文件\meta-data", r"E:\emby\高清影视", False, False)
    # 4、115网盘内的数据绑定
    # source_relation_targer([r"Y:\数据工厂\已处理"], [r"Y:\数据工厂\脏数据"])
    # 5、建立映射
    # mapping_file_with_video(r"E:\emby\高清动画", r"E:\emby\文件映射")
    # 6、删除映射
    # remove_lik(r'E:\emby\高清动漫')

    # movie_video_subtitle(r'E:\emby\高清影视', r'E:\emby\文件映射')
    # mirror_gd_local()
    # ss(r'./scrapy_result/mapping_gd_ld-old.json')
    # mirror_gd_local_jav()
    # remove_local_dir()
    # process_tmm_log(r'D:\Program Files\tmm_3.1.7_win\logs\tmm.log', r'E:\meta-data\数据工厂\process')
    # reand_mapping_tmm(gd_root_path=r'Y:\优蛋网盘\影视剧集\香港电影', ld_root_path=r'G:\香港电影')
    # reand_mapping_tmm_new(r'E:\meta-data\数据工厂\process')
    # clear_dir_context(r'E:\meta-data\数据工厂\process')  # 删除视频文件
    # reback_file_by_log()
    # move_dir_to_dir(param_source_dir=r'Y:\2.1、影视合集\data-factory\待删除',
    #                 param_targer_dir=r'Y:\2.1、影视合集\影视资源\正常合集',
    #                 param_will_delete_dir=r'Y:\2.1、影视合集\data-factory\待删除-01',
    #                 param_forced_replace=False)
    # process_gd_dir_path(result_json_path=r'./scrapy_result/final_result.json', source_root_path=r'Y:\动漫资源\国语1080P动漫合集\B', targer_root_path=r'Y:\动漫资源\数据工厂\result')
    # mapping_sigle_file(r"E:\emby\高清影视\突袭 (2011)", r"Y:\优蛋网盘\影视剧集\高清影视")
